#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>

int main(int argc, char *argv[]) {
	int i, j, myrank;
	MPI_Status status;
	MPI_Init(&argc, &argv);
	MPI_Comm_rank(MPI_COMM_WORLD, &myrank);

	if (myrank == 0) {
		void * map;
		int fd;
		struct stat fs;
		fd = open((char*) "bytes.bin", O_RDONLY);

		if (fd == -1) {
			perror("Error opening file for reading");
			exit (EXIT_FAILURE);
		}

		if (fstat(fd, &fs) == -1) {
			perror("Error on fstat");
			exit (EXIT_FAILURE);
		}
		printf("Opening file: %d kb\n", (int) fs.st_size);
		map = mmap(0, fs.st_size, PROT_READ, MAP_SHARED, fd, 0);

		if (map == MAP_FAILED) {
			close (fd);
			perror("Error mmapping the file");
			exit (EXIT_FAILURE);
		}

		MPI_Send(map, 16, MPI_BYTE, 1, 123, MPI_COMM_WORLD);
	} else if (myrank == 1) {
		void* resv = malloc(16);
		MPI_Recv(resv, 16, MPI_BYTE, 0, 123, MPI_COMM_WORLD, &status);
		char * ptr = (char*) resv;
		int * iptr = (int*)	ptr;
		printf("%d %d\n", iptr[0], iptr[1]);
		float * fptr= (float*) (ptr+ 8);
		printf("%.1f %.1f\n", fptr[0], fptr[1]);

		free (resv);

	}
	MPI_Finalize();
	return 0;
}
